import React from 'react';
import {
  Form,
  Input,
  Button,
  Table,
  Icon,
  Radio,
  InputNumber,
  Checkbox,
  Modal,
  message,
  notification,
  Affix,
  Upload,
  Select
} from 'antd';

import InnerTable from 'components/DBTable/InnerTable.js';
import ajax from '../../../utils/ajax';

const FormItem = Form.Item;
const ButtonGroup = Button.Group;
const Option = Select.Option;

var _this;

/**
 * 内部表格组件
 */
class LoadPictureInnerTable extends InnerTable {


  /**
   * 构造器，好像是用来初始化的？
   * @param props
   */
  constructor(props) {
    super(props);
    this.state = {
      ...this.state,
      upOpt: ['OPTION_SAVE'],
    };
    // 0 返回file和image 
    // 1 file 
    // 2 image
    this.responseStatus = 2;
  }



  /**
   * 这里好像是用来配置那些按钮之类的
   * @returns {Array}
   */
  prepareToolBar = function () {

    let isButtondisabled = false;

    if (this.state.selectedRowKeys.length > 0) {  // 是否选择
      isButtondisabled = true;
    }

    if (this.state.selectedRowKeys.length > 1) {  // 是否选择了多项
      isButtondisabled = false;
    }

    //上面是选择框的那个配置
    var items = [];

    if (this.props.tableConfig.showUpload) {
      items.push(<Button key='audioUpBtn' type="primary" disabled={!isButtondisabled} onClick={this.onClickUpLoadPicture}>
        <Icon type="edit"/>上传图片
      </Button>)
    }
    return items;

  }

  /**
   * 转换表单里面的日期，这里会覆盖父类的方法
   * @param obj
   * @returns {*}
   */
  handleData = (obj) => {
    let fileList = this.state.fileList;
    console.log("fileList里面的数据是", fileList);
    console.log("obj里面的数据是", obj);
    if(obj.actionState != 3 && (!fileList || fileList[0].status != "done")){
      notification.error({
        message: "图片上传中",
        description: "请等待~~~"
      });
      return;
    }

    if (obj.actionState == this.modalActionState.Insert
      || obj.actionState == this.modalActionState.Update) {
      var data = obj.params;
      data.showAtStr = data.showAtStr.format('YYYY-MM-DD HH:mm:ss');
      delete data.imageFile;
    }
    return obj;
  }

  /**
   * 点击form 表单里面的文件上传调用的方法
   */
  onImageFileChange = (info) =>{
    let fileList = info.fileList;
    if (info.file.status == "error") {
      notification.error({
        message: "图片上传失败",
        description: "请联系管理员~~~"
      });
      return;
    }
    console.log("fileList 里面的数据是", fileList);

    if (fileList.length > 1) {
      fileList = fileList.slice(-1); //最多只能有一个文件
    }

    if (info.file.response) {
      fileList = fileList.map((file) => {
        file.url = file.response.data.imgUrl;
        return file;
      });
      let fileKey = info.file.response.data.key;
      console.log("avatar 里面的数据是", fileKey);
      this.props.form.setFieldsValue({avatar:fileKey});
    }
    
    this.setState({ fileList: fileList });
    this.props.form.setFieldsValue({imageFile:fileList});
  }

  handleModalOk = () => {
    // console.log("哈哈");
    // 将表单中的undefined去掉
    // 表单传过来的主键是逗号分隔的字符串, 这里转换成数组
    const {modalForm} =this.state;
    if(!modalForm){
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          const newObj = {};
          const primaryKeyArray = [];
          const oldObj = this.props.form.getFieldsValue();
          if(!oldObj.name) {
            oldObj.name = "秒借贷";
          }
          for (const key in oldObj) {
            if (!oldObj[key])
              continue;

            if (key === this.primaryKey && typeof oldObj[key] === 'string') {
              for (const str of oldObj[key].split(', ')) {
                // 按schema中的约定, 主键只能是int/varchar
                if (this.primaryKeyType === 'int') {
                  primaryKeyArray.push(parseInt(str));
                } else {
                primaryKeyArray.push(str);
                }
              }
            } else {
              newObj[key] = oldObj[key];
            }
          }
      
          if (this.primaryKey && primaryKeyArray.length > 0) {
            newObj[this.primaryKey] = primaryKeyArray;
          }

          if (this.state.modalState==this.modalActionState.Update)
          {
            if (this.primaryKey) {
            newObj[this.primaryKey] = this.state.selectedRowKeys[0];
            }
          }

          if (this.state.modalState==this.modalActionState.Insert) {
            this.handleInsert(newObj);
          }
          else if (this.state.modalState==this.modalActionState.Update) {
            this.handleUpdate(newObj);
          }
        }
      });
    }

  }


  /**
   * 点击新增之前，将上传过的文件给删除了
   */
  handleInsertBefore = () =>{
    delete this.state.fileList;
  }

  //-----------------------------------------------------------------------------------------------------------------------------------------------------
  // ------------------------------------------------------下面是单独的上传框，先不删除，以后可能会用到--------------------------------------------------------'
  // -----------------------------------------------------------------------------------------------------------------------------------------------------。



//点击上传启动图
  onClickUpLoadPicture = () =>{
    //框可见
    this.setState({modalUpAudioVisible: true, defaultFileList : this.state.selectedRows[0].imgUrl});
    this.initDefaultFile();
  }

  initDefaultFile = () => {
    let defaultFileObj = [];
    let defaultFileItemPropsItem = this.state.defaultFileList;
    console.log(defaultFileItemPropsItem);

    if (defaultFileItemPropsItem) { //处理已上传的图片
      let defaultFileItem = {};
      defaultFileItem.name = "已上传的图片";
      defaultFileItem.status = "done";

      defaultFileItem.url = defaultFileItemPropsItem;
      defaultFileObj.push(defaultFileItem);
      this.setState({ defaultFileObj: defaultFileObj });
    }
    else {
      this.setState({ defaultFileObj: [] });
    }
  }

  preDealTableData = (obj,newObj) => {
    if (obj.imgUrl == undefined) {
      newObj.thumbnail = '';
      return
    }
    if (!newObj.thumbnail){
      newObj.thumbnail = obj.imgUrl.split('?')[0] + "?imageView2/2/w/60/h/60/q/20";
    }
    newObj.width = obj.width + '*' + obj.height;
  }

  /**
   * 创建上传的那个框
   * @returns {XML}
   */
  getUniqueModal=()=>{
    return (
      <div>
        <Modal title="启动图" visible={this.state.modalUpAudioVisible} onOk={this.handleModalUpImageOk}
               onCancel={this.hideModalCancleUpImage} onClose={this.handleClose}>
          <div>
            <Upload action="/image/upload"
                    onChange={this.handleUpChange}
                    onRemove={this.handleRemove}
                    fileList={this.state.defaultFileObj}>
              <Button type="ghost">
                <Icon type="upload" />上传图片
              </Button>
            </Upload>
          </div>
        </Modal>
      </div>);
  }

  handleClose = () =>{
    this.setState({modalUpAudioVisible:false});
  }

  /**
   *点击确定执行的方法
   * @type {{}}
   */
  handleModalUpImageOk = () =>{
    _this=this;
    ajax.post({
      url:"/loadpicture/update",
      params:{id:this.state.selectedRowKeys.join(""),avatar:this.state.imgKey},
      success:function(res){
        _this.setState({ modalUpAudioVisible: false });
        _this.props.refresh(); //刷新列表
        message.success('修改成功');
      }
    })
  }

  /**
   * 点击取消调用的方法
   */
  hideModalCancleUpImage = () =>{
    this.setState({modalUpAudioVisible:false});
  }

  /**
   * 选择文件执行的方法
   * @param info
   */
  handleUpChange = (info) => {
    let fileList = info.fileList;
    console.log(fileList.name);
    if (fileList.length > 1) {
      fileList = fileList.slice(-1); //最多只能有一个图片

      fileList = fileList.map((file) => {
        if (file.response) {
          file.imgUrl = file.response.data.imgUrl;
        }
        return file;
      });
      console.log(fileList.name);
      this.setState({defaultFileObj: fileList});

      if (info.file.response) {
        this.props.uploadVideo(info.file.response.data.key);
      }

    } else {
      this.setState({ defaultFileObj: fileList });
      if (info.file.response) {
        this.setState({imgKey:info.file.response.data.key, defaultfile:info.file.response.data});
      }
    }
  }

  handleRemove = () =>{

  }

}

export default LoadPictureInnerTable;
